<template>
  <el-form label-width="100px">
    <el-form-item label="用户账号" >
      <el-input v-model="modelData.name" disabled> </el-input>
    </el-form-item>

    <el-form-item label="分配角色" >
      <el-tree
        ref="tree"
        :props="props"
        :data="dataTree"
        :default-checked-keys="checkedNode"
        node-key="id"
        show-checkbox
        check-strictly
        @check-change="handleCheckChange">
      </el-tree>
    </el-form-item>

    <el-form-item>
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { putUserRole } from 'api/admin/user'
import { fetchTree } from 'api/admin/role'
export default {
  name: 'element',
  data () {
    return {
      modelData: {
        id: 0,
        name: undefined,
        roleId: 0
      },
      modelAuth: [
      ],
      props: {
        label: 'label',
        children: 'children'
      },
      dataTree: [],
      checkedNode: []
    }
  },
  created () {
    console.log('created')
    fetchTree().then(response => {
      this.dataTree = response.data
    })
  },
  mounted () {
    console.log('mounted')
    this.checkedNode = []
  },
  methods: {
    setModel (data) {
      console.log('setModel')
      this.$refs.tree.setCheckedNodes([])
      if (data) {
        this.modelData.id = data.id
        this.modelData.name = data.username
        this.modelData.roleId = data.roleId
        this.checkedNode = [this.modelData.roleId]
        // getObj(data.id).then(response => {
        //   this.modelAuth = response.data
        //   this.checkedNode = response.data.roleIds
        // })
      }
    },
    handleCheckChange (item, checked) {
      // 单选
      if (checked) {
        this.$refs.tree.setCheckedNodes([{
          id: item.id,
          text: item.text
        }])
      }
    },
    handleSubmit () {
      // console.log(this.checkedNode)
      // console.log()
      this.update()
    },
    handleCancel () {
      this.$emit('cancel')
    },
    update () {
      let ids = this.$refs.tree.getCheckedKeys()
      putUserRole(this.modelData.id, ids.toString()).then(response => {
        let code = parseInt(response.code)
        if (code === 0) {
          this.$message.success('修改成功')
          this.complete()
        }
      })
    },
    complete () {
      this.checkedNode = []
      // this.$refs.form.resetFields()
      this.$emit('complete')
    }
  }
}
</script>
